package com.xy.weixin.tuling;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xy.weixin.tuling.entity.BaseEntity;
import com.xy.weixin.tuling.entity.FlightEntity;
import com.xy.weixin.tuling.entity.InfoEntity;
import com.xy.weixin.tuling.entity.NewsEntity;
import com.xy.weixin.tuling.entity.TrainEntity;

public class TulingApiProcess {
	
	private static String APIKEY = "dc70cbab00cf4a9cdf98ebe80881586a";
	private static String APIURL= "http://www.tuling123.com/openapi/api?key=";
	
	/**
	 * 调用图灵机器人api接口，获取智能回复内容，解析获取自己所需结果 
	 * 
	 * @param content
	 * @return
	 */
	public BaseEntity getTulingResult(String content) {
		BaseEntity entity = null;
		try {
			String INFO = URLEncoder.encode(content, "utf-8");
			String getURL = APIURL + APIKEY
					+ "&info=" + INFO;
			
			//如果要是的代理请使用以下代码
			//在你发起Http请求之前设置一下属性  
//			System.setProperty("http.proxyHost", "10.1.2.11");  
//			System.setProperty("http.proxyPort", "31151");
			
			URL getUrl = new URL(getURL);
			HttpURLConnection connection = (HttpURLConnection) getUrl
					.openConnection();
			connection.connect();

			// 取得输入流，并使用Reader读取
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "utf-8"));
			StringBuffer sb = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			
			//解析返回值
			JSONObject object = JSON.parseObject(sb.toString());
			int resultCode = object.getIntValue("code");
			switch (resultCode) {
			case 100000:	//文本类数据
				//entity = JSON.parseObject(sb.toString(), BaseEntity.class);
				entity = JSON.parseObject(sb.toString(), new TypeReference<BaseEntity<InfoEntity>>(){});
				break;
			case 305000:	//列车
				entity = JSON.parseObject(sb.toString(), new TypeReference<BaseEntity<TrainEntity>>(){});
				break;
			case 306000:	//航班
				entity = JSON.parseObject(sb.toString(), new TypeReference<BaseEntity<FlightEntity>>(){});
				break;
			case 200000:	//网址类数据
				//entity = JSON.parseObject(sb.toString(), BaseEntity.class);
				entity = JSON.parseObject(sb.toString(), new TypeReference<BaseEntity<InfoEntity>>(){});
				break;	
			case 302000:	//新闻
				entity = JSON.parseObject(sb.toString(), new TypeReference<BaseEntity<NewsEntity>>(){});
				break;
			case 308000:	//菜谱、视频、小说
				entity = JSON.parseObject(sb.toString(), new TypeReference<BaseEntity<InfoEntity>>(){});
				break;
			default:	//其他
				break;
			}
			reader.close();
			// 断开连接
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return entity;
	}
}
